from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from .models import City, DataCenter, Host, HostStatistics
from .serializers import CitySerializer, DataCenterSerializer, HostSerializer, HostStatisticsSerializer
import subprocess
from django.utils import timezone


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class DataCenterViewSet(viewsets.ModelViewSet):
    queryset = DataCenter.objects.all()
    serializer_class = DataCenterSerializer


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'])
    def check_reachable(self, request, pk=None):
        host = self.get_object()
        try:
            # 使用系统ping命令检查可达性
            result = subprocess.run(['ping', '-c', '1', '-W', '1', host.ip_address],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            is_reachable = result.returncode == 0
            host.is_reachable = is_reachable
            host.last_reachable_check = timezone.now()
            host.save()

            return Response({
                'host': host.hostname,
                'ip_address': host.ip_address,
                'is_reachable': is_reachable,
                'last_checked': host.last_reachable_check
            })
        except Exception as e:
            return Response({
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class HostStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = HostStatistics.objects.all()
    serializer_class = HostStatisticsSerializer